import keyboard
from bdtime import tt


#
# keyboard.press_and_release('shift+s, space')
#
# keyboard.write('The quick brown fox jumps over the lazy dog.')
#
# keyboard.add_hotkey('ctrl+shift+a', print, args=('triggered', 'hotkey'))
#
# # Press PAGE UP then PAGE DOWN to type "foobar".
# keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))



import json
import os


output_dir = 'tempdir/data'
os.makedirs(output_dir, exist_ok=True)

f_path = os.path.join(output_dir, 'recorded.txt')

os.makedirs('tempdir/data', exist_ok=True)


def save_recorded(recorded, f_path):
    e_dc_ls = [json.loads(e.to_json()) for e in recorded]
    e_js = json.dumps(e_dc_ls, indent=2)
    with open(f_path, 'w+') as f:
        f.write(e_js)


def load_recorded(f_path):
    from keyboard._keyboard_event import KeyboardEvent

    assert os.path.exists(f_path), f'[{f_path}]不存在?'
    # 从文件中加载JSON数据
    with open(f_path, 'r') as file:
        res = json.load(file)
    res = [KeyboardEvent(**ee) for ee in res]
    return res


if __name__ == '__main__':
    tt.sleep(1)

    print('--- ready ~~~')

    # Blocks until you press esc.
    keyboard.wait('esc')

    print('--- start!')
    tt.sleep(0.5)

    if 0:
        # Record events until 'esc' is pressed.
        recorded = keyboard.record(until='esc')
        save_recorded(recorded, f_path)
        # Then replay back at three times the speed.

    recorded = load_recorded(f_path)

    print('--- play!')
    tt.sleep(0.5)
    keyboard.play(recorded, speed_factor=3)

    # rr = load_recorded(f_path)
    # ee = rr[0]
    # e = recorded[0]
    # type(e)
    # keyboard.play(r1, speed_factor=3)
    #
    # 1
    # type(recorded)
    # recorded

    # Type @@ then press space to replace with abbreviation.
    # keyboard.add_abbreviation('@@', 'my.long.email@example.com')

    # Block forever, like `while True`.
    # keyboard.wait()
    print('------- end')
